package io.kimmking.kmq.core;

import lombok.Data;

import java.util.concurrent.TimeUnit;

@Data
public final class CircleQueue {

    private int capacity;
    // 消息头
    private int head;
    // 消息尾
    private int last;
    // 消息数组
    private KmqMessage[] messages;

    // final ReentrantLock lock = new ReentrantLock();
    // private final Condition notEmpty = lock.newCondition();
    // private final Condition notFull = lock.newCondition();

    public CircleQueue(String topic, int capacity) {
        if (capacity <= 0) throw new IllegalArgumentException();
        if (null != topic && "".equals(topic.trim())) throw new IllegalArgumentException();
        this.capacity = capacity;
        this.messages = new KmqMessage[capacity];
    }

    public int getSize() {
        return (capacity + last - head) % capacity;
    }

    public boolean isFull() {
        return getSize() == capacity;
    }

    public boolean isEmpty() {
        return head == last;
    }

    public KmqMessage poll(long timeout, TimeUnit unit) {
        if (isEmpty()) {
            return null;
        }
        KmqMessage msg = messages[head];
        head = (head + 1) % capacity;
        return msg;
    }

    public boolean offer(KmqMessage msg) {
        if (isFull()) {
            System.out.println("队列已满~");
            return false;
        }
        System.out.print("队列未满~");
        System.out.println(last);
        messages[last] = msg;
        last = (last + 1) % capacity;
        return true;
    }


}
